//
//  MaterialAcceptCreateController.m
//  ERP
//
//  Created by QA on 16/10/9.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MaterialAcceptCreateController.h"
#import "GETableView.h"

#import "GEInputTableViewCell.h"
#import "FileUploadModel.h"
#import "UploadViewController.h"
#import "PreviewLocalFileHelper.h"
#import "GEObjectButton.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "NSKeyedArchiverUserLogin.h"
#import "GEPickerTextField.h"
#import "NSDictionary+DataFormat.h"
#import "MaterialAcceptCreateCell.h"

#import "AutoTextTableViewCell.h"
#import "MaterialAcceptNextCell.h"

#import "EYDeductPopupView.h"

@interface MaterialAcceptCreateController()

@property (nonatomic,strong) IBOutlet GETableView *tableView;
@property (nonatomic, strong) NSMutableArray *accessoryArray;

@property (nonatomic,strong) NSMutableArray *subMBaseData;
@property (nonatomic,strong) NSDictionary *backDictionary;

@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic, assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation MaterialAcceptCreateController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"材料验收"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    self.resultData = [NSMutableArray array];
    
    self.backDictionary = self.value;
    [self setShowInfoArray:self.backDictionary];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    
    //获取扣重项目
    [self getNetWorkDataYCID:_backDictionary];
}

- (void)setShowInfoArray:(NSDictionary*)dic
{
    NSMutableArray *subMBase = [NSMutableArray array];
    [self addContractInfoKey:@"磅单编号" toKey:@"磅单编号：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"材料名称" toKey:@"材料名称：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"供应商" toKey:@"供  应  商：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"进厂时间" toKey:@"进厂时间：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"车辆编号" toKey:@"车辆编号：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"毛重" toKey:@"材料毛重：" defaults:@"未知" format:@"%@公斤" form:dic toArray:subMBase];
    [self addContractInfoKey:@"仓位" toKey:@"材料仓位：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    [self addContractInfoKey:@"称量员" toKey:@"过磅人员：" defaults:@"未知" format:nil form:dic toArray:subMBase];
    self.subMBaseData = subMBase;
    
    [self.tableView reloadData];
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getPassingParameter:(id)object
{
    //提前加载预绘制项目
    NSInteger section = [self numberOfSectionsInTableView:_tableView];
    for (int i=0; i<section; i++) {
        NSInteger row = [self tableView:_tableView numberOfRowsInSection:i];
        for(int j=0; j<row; j++){
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
            [self tableView:_tableView cellForRowAtIndexPath:indexPath];
        }
    }
}

#pragma mark 网络获取数据

- (void)getNetWorkDataYCID:(NSDictionary*)mDictionary
{
    NSString *ycId = [mDictionary objectFormatStringForKey:@"材料ID"];
    
    //@状态（1待验收，2已验收）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCYS_KZLX_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"原材ID" value:ycId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
    
}

#pragma mark UIButton Event

//通过验收
- (void)passSelector:(UIButton *)button
{
    [self submitTheLogGenerateHandle];
}

- (void)submitTheLogGenerateHandle
{
    UITextField *jjfaField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:0 inSection:3];
    NSString *handleText = [jjfaField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    //获取用户信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //处理照片信息
    NSMutableString *imageURLs = [NSMutableString string];
    for(FileUploadModel *model in self.accessoryArray){
        NSDictionary *jsonDictionary = [model getFileInfo];
        NSString *filePath = [jsonDictionary objectFormatForKey:@"filePath"];
        [imageURLs appendFormat:@"%@,",filePath];
    }
    if(imageURLs.length > 0)
    [imageURLs deleteCharactersInRange:NSMakeRange(imageURLs.length - 1, 1)];
    
    //扣重项目处理
    NSMutableString *tareString = [NSMutableString string];
    for(int i=0;i<self.resultData.count;i++){
        MaterialAcceptNextCell *cell = [self.tableView getCellViewInRow:i inSection:2];
        if(cell.type == 0) continue;
        
        NSString *itemValue = @"";
        if(cell.type == 1) itemValue = [NSString stringWithFormat:@"%@,null,%@", cell.ycid, cell.inputValue];
        if(cell.type == 2) itemValue = [NSString stringWithFormat:@"%@,%@,null", cell.ycid, cell.inputValue];
        [tareString appendFormat:@"%@|",itemValue];
    }
    if(tareString.length > 0)
    [tareString deleteCharactersInRange:NSMakeRange(tareString.length - 1, 1)];
    
    NSString *ID = [self.backDictionary objectFormatIntStringForKey:@"Id"];
    NSString *ycId = [self.backDictionary objectFormatStringForKey:@"材料ID"];
    NSString *gysId = [self.backDictionary objectFormatStringForKey:@"供应商ID"];
    NSString *bdh = [self.backDictionary objectFormatStringForKey:@"磅单编号"];
    NSString *clbh = [self.backDictionary objectFormatStringForKey:@"车辆编号"];
    NSString *clmc = [self.backDictionary objectFormatStringForKey:@"材料名称"];
    NSString *mz = [self.backDictionary objectFormatStringForKey:@"毛重"];
    NSString *jcsj = [self.backDictionary objectFormatStringForKey:@"进厂时间"];
    NSString *cw = [self.backDictionary objectFormatStringForKey:@"仓位"];
    NSString *gys = [self.backDictionary objectFormatStringForKey:@"供应商"];
    NSString *gby = [self.backDictionary objectFormatStringForKey:@"称量员"];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setShowLoadingPrompt:self.navigationController labelText:@"正在提交"];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"YCYS_ADD"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    [content addParameterKey:@"用户ID" value:userInfo.Id];
    [content addParameterKey:@"站点ID" value:model.stationId];
    [content addParameterKey:@"材料ID" value:ycId];
    [content addParameterKey:@"供应商ID" value:gysId];
    [content addParameterKey:@"车辆编号" value:clbh];
    [content addParameterKey:@"ID" value:ID];
    [content addParameterKey:@"磅单号" value:bdh];
    [content addParameterKey:@"材料名称" value:clmc];
    [content addParameterKey:@"毛重" value:mz];
    [content addParameterKey:@"进厂时间" value:jcsj];
    [content addParameterKey:@"仓位" value:cw];
    [content addParameterKey:@"供应商" value:gys];
    [content addParameterKey:@"过磅员" value:gby];
    [content addParameterKey:@"备注" value:handleText];
    [content addParameterKey:@"扣重明细" value:tareString];
    [content addParameterKey:@"图片地址" value:imageURLs];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self showSuccessHUDText:@"验收成功"];
            if(self.backResultDelagate) [self.backResultDelagate backResultDataKey:nil dataValue:self.backDictionary];
            
            // 延迟2.2秒执行：
            double delayInSeconds = 2.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
            
        } else{
            [self showErrorHUDText:@"验收失败"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"验收失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"验收失败"];
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) {
        return self.accessoryArray.count + 1;
        
    } else if(section == 2) {
        NSInteger count = self.resultData.count;
        return count > 0 ? count : 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"CreateContractViewController%ld%ld",indexPath.section,indexPath.row];
    GEInputTableViewCell *cell = [self.tableView getCellViewInRow:indexPath.row inSection:indexPath.section];
    if (cell != nil) return cell;
    
    //合同基本信息
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        cell.isChangeWidth = YES;
        [cell setDataArray:self.subMBaseData];
        return cell;
    }
    
    //见证取样
    else if(indexPath.section == 1){
        GEInputTableViewCell *cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.bounds = CGRectMake(0, 0, cell.bounds.size.width, 48);
        
        if (indexPath.row < self.accessoryArray.count) {
            FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
            [self drawRowFileCell:cell model:model indexPath:indexPath];
        } else {
            UIImage *image = [UIImage imageNamed:@"button_bg_add"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2, image.size.width, image.size.height)];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
    
    //扣重原因
    else if(indexPath.section == 2){
        if (self.orderContentState == 3) {
            static NSString *Identifier = @"MaterialAcceptNextCell";
            //MaterialAcceptNextCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
            MaterialAcceptNextCell *cell = [self.tableView getCellViewInRow:indexPath.row inSection:indexPath.section];
            if (!cell){
                cell = [[MaterialAcceptNextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
                NSDictionary *dictionary = [self.resultData objectAtIndex:indexPath.row];
                cell.title.text = [dictionary objectFormatStringForKey:@"Item"];
                
                cell.ycid = [dictionary objectFormatStringForKey:@"Id"];
                cell.button.tag = indexPath.row;
                [cell.button addTarget:self action:@selector(instructSelector:) forControlEvents:UIControlEventTouchUpInside];
                [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
            }
            return cell;
            
        } else {
            GEInputTableViewCell *cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
            cell.contentView.frame = CGRectMake(10, 0, SuperWidth - 20, 50);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"暂无扣重项目";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    //解决方案
    else if(indexPath.section == 3){
        GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            UITextView *field = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, cell.contentView.frame.size.width - 10, 110)];
            field.font = [UIFont systemFontOfSize:15.0];
            field.textColor = [UIColor darkGrayColor];
            field.textAlignment = NSTextAlignmentLeft;
            [cell.contentView addSubview:field];
            [self.tableView setCellView:cell inRow:indexPath.row inSection:indexPath.section];
        }
        return cell;
    }
    
    //处理按钮
    else if(indexPath.section == 4){
        MaterialAcceptCreateCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MaterialAcceptCreateCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier index:0];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            
            [cell.passButton addTarget:self action:@selector(passSelector:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //基本信息不添加
    if(section == 4) return nil;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SuperWidth - 30, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if(section == 0){
        lable.text = @"过磅材料明细";
    } else if(section == 1){
        lable.text = @"材料取样";
    } else if(section == 2){
        lable.text = @"材料扣重项目";
    } else if(section == 3){
        lable.text = @"验收处理情况";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 4) return 0.0001;
    else return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.subMBaseData];
        return cell.contentView.frame.size.height;
        
    } else if (indexPath.section == 1) return 50;
    else if (indexPath.section == 2) return self.resultData.count>0 ? 44 : 50;
    else if (indexPath.section == 3) return 120;
    else return 50;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 2){ //扣重项目
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getNetWorkDataYCID:_backDictionary];
            
        } else if(self.orderContentState == 3) { //加载成功
            MaterialAcceptNextCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            GEObjectButton *button = [[GEObjectButton alloc] init];
            button.object = cell;
            [self refuseSelector:button];
        }
    }
    
    //添加附件
    else if (indexPath.section == 1 && indexPath.row ==([self tableView:nil numberOfRowsInSection:1] - 1)) {
        UploadViewController *abstractView = [[UploadViewController alloc] init];
        [abstractView setNumberType:@"2" extension:@"bmp,jpg,gif,png"];
        
        abstractView.key = @"AccessoryFile";
        abstractView.backResultDelagate = self;
        [self.navigationController pushViewController:abstractView animated:YES];
    }
    
    //附件预览
    else if (indexPath.section == 1){
        FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
        PreviewLocalFileHelper *preview = [PreviewLocalFileHelper instantiation];
        [preview previewViewController:self localFile:model.filePath];
    }
    
    //键盘事件处理
    UITextField *textField = [self.tableView getCellSaveClass:[UITextField class] pathForRow:indexPath.row inSection:indexPath.section];
    if (textField) [textField becomeFirstResponder];
    
}


//添加文件
- (void)drawRowFileCell:(UITableViewCell*)cell model:(FileUploadModel *)model indexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = cell.frame.size;
    cellSize.height = 50;
    cellSize.width = SuperWidth;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, cellSize.height - 10, cellSize.height - 10)];
    imageView.image = [FileTypeIcon setFileTypeIcon:model.filePath];
    [cell.contentView addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, 3, cellSize.width - cellSize.height - 60, cellSize.height/2)];
    titleLabel.text = model.fileName;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:titleLabel];
    
    NSString *fileSize = [FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%lld",model.fileSize]];
    UILabel *field = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, cellSize.height/2 - 2, cellSize.width - cellSize.height - 10, cellSize.height/2)];
    field.font = [UIFont systemFontOfSize:12.0];
    field.text = [NSString stringWithFormat:@"文件大小：%@", fileSize] ;
    field.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:field];
    
    GEObjectButton *button = [GEObjectButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(cellSize.width - 70, 0, cellSize.height, cellSize.height);
    [button setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(delFileSelector:) forControlEvents:UIControlEventTouchUpInside];
    button.object = @[@(indexPath.section), model];
    [cell.contentView addSubview:button];
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:lineView];
}

#pragma mark -
#pragma mark Button Event

- (void)delFileSelector:(GEObjectButton*)button
{
    NSArray *array = button.object;
    NSInteger section = [array[0] integerValue];
    id delValue = array[1];
    
    if (section == 1 && self.accessoryArray.count>0) {
        NSInteger index = [self.accessoryArray indexOfObject:delValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.accessoryArray removeObject:delValue];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
    }
    
}

//材料扣重项目选址
- (void)refuseSelector:(id)sender
{
    GEObjectButton *button = sender;
    MaterialAcceptNextCell *cell = button.object;
    
    [EYDeductPopupView popViewWithTitle:cell.title.text contentText:@"请选择材料扣重方式" cancelButton:@"不扣重"
                              okButton:@"确定" type:EYInputPopupView_Type_multi_line
                           cancelBlock:^{
                               NSLog(@"left button cancel clicked");
                               cell.type = 0;
                               cell.inputValue = nil;
                               cell.kzField.text = [NSString stringWithFormat:@""];
                               
                           } confirmBlock:^(UIView *view, NSInteger type, NSString *text) {
                               NSLog(@"left button confirmBlock clicked");
                               if(text.length <= 0) return;
                               
                               cell.type = type + 1;
                               cell.inputValue = text;
                               if(type == 0) cell.kzField.text = [NSString stringWithFormat:@"扣重%@%%",text];
                               if(type == 1) cell.kzField.text = [NSString stringWithFormat:@"扣重%@KG",text];
                               
                           } dismissBlock:^{
                               NSLog(@"left button dismiss clicked");
                           }];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    NSArray *array = backValue;
    if (!(array && array.count>0)) return;
    
    if([key isEqualToString:@"AccessoryFile"]){
        //添加附件
        if ([backValue isKindOfClass:[NSArray class]]) {
            NSMutableArray *insertIndexPath = [NSMutableArray array];
            for (int i=0;i<array.count;i++) {
                id value = [array objectAtIndex:i];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
                [insertIndexPath addObject:indexPath];
                [self.accessoryArray insertObject:value atIndex:0];
            }
            
            if (insertIndexPath.count>0) {
                [self.tableView beginUpdates];
                [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
                [self.tableView endUpdates];
            }
        }
    }
}

#pragma mark - UIButton Event

- (void)instructSelector:(UIButton*)button
{
    NSDictionary *dictionary = [self.resultData objectAtIndex:button.tag];
    NSString *message = [dictionary objectFormatStringForKey:@"Remarks"];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"扣重验收说明" message:message delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

@end

